package com.itheima.reggie.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.itheima.reggie.dao.CategoryDao;
import com.itheima.reggie.dao.DishDao;
import com.itheima.reggie.dao.SetmealDao;
import com.itheima.reggie.entity.Category;
import com.itheima.reggie.entity.Page;
import com.itheima.reggie.exception.CustomerException;
import com.itheima.reggie.service.CategoryService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;
@Service
public class CategoryServiceImpl implements CategoryService {
    @Autowired
    private CategoryDao categoryDao;
    @Autowired
    private DishDao dishDao;
    @Autowired
    private SetmealDao setmealDao;

    @Override
    public void add(Category category) {
        category.setCreateTime(LocalDateTime.now());
        category.setUpdateTime(LocalDateTime.now());
        categoryDao.add(category);
    }

    @Override
    public Page<Category> findByPage(Integer page, Integer pageSize) {
        PageHelper.startPage(page, pageSize);
        List<Category> categoryList = categoryDao.findByPage();
        PageInfo<Category> pageInfo = new PageInfo<>(categoryList);
        Page<Category> pageRes = new Page<>();
        pageRes.setPage(pageInfo.getPageNum());
        pageRes.setPageSize(pageInfo.getPageSize());
        pageRes.setTotal(pageInfo.getTotal());
        pageRes.setRecords(pageInfo.getList());
        return pageRes;
    }

    @Override
    public void delById(Long id) {
        // 判断菜品是否有分类
        Integer dish = dishDao.findCountByCateId(id);
        if(dish > 0) {
            throw new CustomerException("该类别已经关联菜品不能直接删除");
        }
        // 判断套餐是否有分类
        Integer setmeal = setmealDao.findCountByCateId(id);
        if (setmeal > 0) {
            throw new CustomerException("该类别已经关联套餐不能直接删除");
        }
        categoryDao.delById(id);
    }

    @Override
    public void update(Category category) {
        categoryDao.update(category);
    }

    @Override
    public List<Category> findAll() {

        List<Category> list = categoryDao.findAll();
        return list;
    }

    @Override
    public List<Category> list(Integer type) {

        List<Category> categoryList = categoryDao.list(type);
        return categoryList;
    }
}
